<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root"></div>

<script>
    let root = document.querySelector("#root")
    /*
    1.createElement 把function变成对象
    element是 react 元素
    node 是dom 元素

    实现
    react.createElement(
    "h1", //type
    {id:"title"}, //prop
    react.createElement( //children
        "h2",
        {id:"title2"},
        "内容2"
    )
    "title"
    )
    //这里生成 
    <h1 id="title">
    title
    <h2 id="title2"> 内容2</h2> 
    </h1>

    createElement(type,props,children)
    难点在于组装成一个object ？？？ 
    还真是。因为最主要的render逻辑没有讲
    形参的...xxx。xxx会变成 [xxx,xxx]
    形参的[...xxx]。[] 会比 ...优先级高. 扩展运算符最好还是一个用 

    */
    function createElement(type, props, ...children) {
        return {
            type,
            props: {
                ...props,
                children: children.map((child) => {
                    return typeof child === 'object' ? child : createTextElement(child)
                }),
            },
        };
    }
    function createTextElement(text) {
        return {
            type: 'TEXT_ELEMENT',
            props: {
                nodeValue: text,
                children: [],
            },
        };
    }

    let fiber = createElement("div", { id: "test" ,},
        "这里是文本节点", createElement("h3", { id: "test",style:"color:red" },
            "这里是文本节点"))

    console.log(fiber)
    /**
     * 
    {
        "type": "div",
        "props": {
            "id": "div",
            "children": [
                {
                    "type": "TEXT_ELEMENT",
                    "props": {
                        "nodeValue": "这里是文本节点",
                        "children": []
                    }
                },
                {
                    "type": "TEXT_ELEMENT",
                    "props": {
                        "nodeValue": "测试",
                        "children": []
                    }
                }
            ]
        }
    }
        */


    /**
     *2.render 的逻辑 
        2.1传入fiber数组和container元素。
        2.2根据type创造子节点createElement 赋值给当前dom
        2.3过滤children渲染子元素 .
        2.4 append dom进 dom里面去
        
    */

    function render(fiber, container) {
        // 创建父节点
        const dom =
            fiber.type == 'TEXT_ELEMENT'
                ? document.createTextNode('')
                : document.createElement(fiber.type);

        // 赋值属性
        Object.keys(fiber.props)
            .filter((key) => key !== 'children')
            .forEach((key) => (dom[key] = fiber.props[key]));

        //渲染子元素
        fiber.props.children.forEach((child) => {
            render(child, dom)
        })
        container.append(dom)
        // return dom;
    }
    render(fiber, root)
</script>

</body>

</html>